import React, { useEffect, useState} from 'react';
import './index.css';
import axios from 'axios';
import {useRegisterState, createAction} from "../../hooks/useRegisterState";
import ReactFileReader from "react-file-reader";

import {Input, Button, Image, Tooltip, message} from 'antd';
import useRegisterTipState from "../../hooks/useRegisterTipState";
import {useHistory} from "react-router-dom";
import registerImg from '../../assets/images/register.png'


const regArr = {
  username: /^\w{8,16}$/,
  password: /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/,
  email: /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/,
  phone: /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/,
};

const userTip = '请输入8-16位用户名，可包含数字、字母、符号、下划线';
const passwordTip = '请输入至少8位密码，包括字母和数字';
const passwordAgainTip = '请再次输入密码，确保一致';
const emailTip = '请输入正确的邮箱格式';
const codeTip = '请输入正确的验证码';
const phone = '请输入正确的联系电话'

function Register() {
  const history = useHistory()
  const {regState, regStateDispatch} = useRegisterState()
  const {tipState, tipDispatch} = useRegisterTipState()
  const [code, setCode] = useState('')
  const [codeUrl, setCodeUrl] = useState('')
  const [base64, setBase64] = useState('')

  async function getCodeImage() {
    axios({
      method: "post",
      url: "/fras/captcha/codeImage",
      responseType: "arraybuffer",
    }).then((res) => {
      let blob = new Blob([res.data], {type: "image/png"});
      let url = window.URL.createObjectURL(blob);
      setCodeUrl(url)
      axios.get('/fras/captcha/code').then(res => {
        setCode(res.data.captchaCode)
      })
    });
  }

  useEffect(()=>{
    getCodeImage()
  }, [])

  const testInput = () => {
    tipDispatch(createAction('USERNAME', !regArr.username.test(regState.username)))
    tipDispatch(createAction('PASSWORD', !regArr.password.test(regState.password)))
    tipDispatch(createAction('PASSWORDAGAIN', !(regState.password === regState.passwordAgain)))
    tipDispatch(createAction('EMAIL', !regArr.email.test(regState.email)))
    tipDispatch(createAction('PHONE', !regArr.phone.test(regState.phone)))
    tipDispatch(createAction('CODE', !(code === regState.code)))
    for (const item in tipState) {
      if (tipState[item]) return false
    }
    return true
  }

  const userRegisterTestAndRegister = async () => {
    if (testInput()) {
      const res = await axios.post(`/fras/captcha/verifyUsername/${regState.username}`)
      if (res.data.code === 200){
        const params = new URLSearchParams()
        params.append('image', base64)
        const regRes = await axios.post(`/fras/register/${regState.username}/${regState.password}/${regState.email}/${regState.phone}`, params)
        console.log(regRes)
        if (regRes.data.code === 200) {
          message.success('注册成功', 1)
          await login()
        }
        else message.error(regRes.data.msg, 1)
        console.log('注册')
      }
      else if(res.data.code === 0){
        message.warning(res.data.msg)
      }
    }
  }

  const login = async () => {
    const params = new URLSearchParams()
    params.append('username', regState.username)
    params.append('password', regState.password)
    const res = await axios.post(`/fras/login`, params)
    if(res.data.code === 200) {
      window.sessionStorage.setItem('my_token', res.data.data.token)
      history.push('/main')
    }
    else {
      message.error(res.data.msg, 1)
    }
  }

  return(
    <div className="register">
      <div className="reg-form">
        <h2>用户注册</h2>
        <div className="reg-form-content">
          <Tooltip placement="right" title={userTip} visible={tipState.username}>
            <Input size="large" placeholder="请输入用户名" value={regState.username} name="username"
                   onChange={(e)=>regStateDispatch(createAction('USERNAME', e.target.value))}/>
          </Tooltip>

          <Tooltip placement="right" title={passwordTip} visible={tipState.password}>
            <Input.Password size="large" placeholder="请输入密码" value={regState.password} name="password"
                            onChange={(e)=>regStateDispatch(createAction('PASSWORD', e.target.value))}/>
          </Tooltip>

          <Tooltip placement="right" title={passwordAgainTip} visible={tipState.passwordAgain}>
            <Input.Password size="large" placeholder="请确认密码" value={regState.passwordAgain}
                            name="passwordAgain" onChange={(e)=>regStateDispatch(createAction('PASSWORDAGAIN', e.target.value))}/>
          </Tooltip>

          <Tooltip placement="right" title={phone} visible={tipState.phone}>
            <Input size="large" placeholder="请输入联系电话" value={regState.phone}
                   name="phone" onChange={(e)=>regStateDispatch(createAction('PHONE', e.target.value))}/>
          </Tooltip>

          <Tooltip placement="right" title={emailTip} visible={tipState.email}>
            <Input size="large" placeholder="请输入邮箱" name="email" value={regState.email}
                   onChange={(e)=>regStateDispatch(createAction('EMAIL', e.target.value))}/>
          </Tooltip>

          <div className="code-group">
            <Tooltip placement="left" title={codeTip} visible={tipState.code}>
              <Input size="large" placeholder="请输入验证码" style={{width: '50%'}} value={code}
                     name="userCode" onChange={(e)=>regStateDispatch(createAction('CODE', e.target.value))}/>
            </Tooltip>
            <Image width={100} src={codeUrl} preview={false} onClick={getCodeImage} alt="加载失败"
                   style={{cursor: 'pointer'}}/>
          </div>

          <Button type="primary" size="large" style={{width: '100%'}}
                  onClick={userRegisterTestAndRegister}>注册</Button>
        </div>
      </div>

      <div className="img-upload">
        <Image
          className="img-box"
          width={200}
          height={200}
          src={base64}
          fallback={registerImg}
        />
        <ReactFileReader
          fileTypes={[".png",".jpg",".gif", "jpeg"]}
          base64
          multipleFiles={!1}
          handleFiles={(files) => {setBase64(files.base64)}}
        >
          <Button>选择图片</Button>
        </ReactFileReader>
        <span className="ps">注：该图片应选择本人正面清晰的免冠照片</span>
      </div>
    </div>
  )
}

export default Register;